# Maintainer: Chocobo1

_realname=zstd
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.4.8
pkgrel=2
pkgdesc="Zstandard - Fast real-time compression algorithm (mingw-w64)"
arch=('any')
url='https://facebook.github.io/zstd/'
license=('BSD')
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-cmake")
source=("https://github.com/facebook/zstd/releases/download/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        zstd-1.4.0-fileio-mingw.patch
        0001-fix-pkgconf-escaping.patch)
sha256sums=('32478297ca1500211008d596276f5367c54198495cf677e9439f4791a4c69f24'
            '210e57fc4bff62e1af1ca8a3da3960de32a91255ba62b057c6bed5b3a7ebb3d5'
            '0501c078581f6439e3de178b5a58183e7bbf738b2cef3a6e0be39eb0d82a806f')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  patch -Np1 -i "${srcdir}/zstd-1.4.0-fileio-mingw.patch"

  # https://github.com/facebook/zstd/pull/2462
  patch -Np1 -i "${srcdir}/0001-fix-pkgconf-escaping.patch"
}

build() {
  [[ -d "${srcdir}"/build-${CARCH} ]] && rm -rf "${srcdir}"/build-${CARCH}
  mkdir -p "${srcdir}"/build-${CARCH} && cd "${srcdir}"/build-${CARCH}

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi
  
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      "${extra_config[@]}" \
      -DZSTD_BUILD_CONTRIB=ON \
      ../${_realname}-${pkgver}/build/cmake

  ${MINGW_PREFIX}/bin/cmake --build .
}


package() {
  cd "${srcdir}"/build-${CARCH}

  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --build . --target install

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
